import 'dart:io';
import 'dart:math';

import 'package:flutter/foundation.dart';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';
import 'package:note/common/common.dart';
import 'package:note/common/tools.dart';
import 'package:note/manager/global.dart';
import 'package:flutter/material.dart';
import 'package:note/widgets/showPhotoView.dart';
import '../../widgets/dialog.dart';
import 'state.dart';

class EditNotePageLogic extends GetxController {
  final EditNotePageState state = EditNotePageState();

  // @override
  // void onInit() {
  //   super.onInit();
  //   state.scrollController.addListener(() {
  //     state.inUp.value = !isScrolledHalfway();
  //     if (state.scrollController.hasClients) {
  //       isOverSize();
  //     }
  //   });
  // }

  @override
  void dispose() {
    state.dispose();
    super.dispose();
  }

  Future<void> onSave() async {
    FocusManager.instance.primaryFocus?.unfocus();
    if (state.contentController.text.isEmpty &&
        state.titleController.text.isEmpty &&
        state.images.isEmpty) {
      //什么都没写，不保存
      Toasts.showToast(Strings.noData);
      return;
    }

    if (state.titleController.text.isEmpty) {
      if (state.contentController.text.isEmpty) {
        //仅有图片
        state.titleController.text = '图片笔记';
      } else {
        int newlineIndex = state.contentController.text.indexOf('\n');
        if (newlineIndex == -1) {
          newlineIndex = state.contentController.text.length;
        }
        if (newlineIndex > 10) {
          newlineIndex = 10;
        }
        state.titleController.text =
            state.contentController.text.substring(0, newlineIndex);
      }
    }

    ///保存图片
    //保存原图文件地址
    List<String> oldImg = [];
    for (int i = 0; i < (state.note.images.length); i++) {
      oldImg.add(state.note.images[i]);
    }
    //清除原图文件地址
    state.note.images.clear();
    //保存新图文件
    for (int i = 0; i < state.images.length; i++) {
      //找到项目文件夹
      final directory = FilePath.getNoteImageDirectory;
      // 生成随机的整数作为文件名的一部分
      int randomInt = Random().nextInt(100000);
      final String newBGPath =
          '$directory/${FilePath.noteImage(state.titleController.text, randomInt.toString(), DateTime.now().toIso8601String())}';
      if (state.images[i].existsSync()) {
        await state.images[i].copy(newBGPath);
        //重写note
        state.note.images.add(newBGPath);
      } else {
        Toasts.showToast('图片丢失！：${state.images[i].path}');
      }
    }
    //清除原图文件
    for (String img in oldImg) {
      if (File(img).existsSync()) {
        File(img).deleteSync();
      }
    }
    state.note.editTime = DateTime.now();
    state.note.data = state.contentController.text;
    state.note.title = state.titleController.text;
    GlobalUtil.setNote(state.note);
    Toasts.showToast(Strings.saveSuccess);
    Get.back(result: state.note);
  }

  void cancelFocus(BuildContext context) {
    FocusScopeNode currentFocus = FocusScope.of(context);
    if (!currentFocus.hasPrimaryFocus && currentFocus.focusedChild != null) {
      FocusManager.instance.primaryFocus?.unfocus();
    }
  }

  void onBody(BuildContext context) {
    FocusScopeNode currentFocus = FocusScope.of(context);
    if (!currentFocus.hasPrimaryFocus && currentFocus.focusedChild != null) {
      FocusManager.instance.primaryFocus?.unfocus();
      return;
    }
    state.contentFocusNode.requestFocus();
  }

  Future<bool> willLeaveEdit() async {
    if (!checkChange()) {
      //未做更改直接退出
      return true;
    }
    Get.dialog(defaultDialog(
      title: Strings.tip,
      content: Strings.noSaveTip,
      sure: Strings.leave,
      sureFunction: () {
        Get.back();
      },
    ));
    return true;
  }

  bool checkChange() {
    List<String> images = [];
    for (final img in state.images) {
      images.add(img.path);
    }
    if (!listEquals(images, state.note.images)) {
      state.hasChange.value = true;
      return true;
    }
    if (state.note.title == state.titleController.text &&
        state.note.data == state.contentController.text) {
      state.hasChange.value = false;
      return false;
    }
    state.hasChange.value = true;
    return true;
  }

  Future<void> onAddPhoto() async {
    List<XFile> imageFile =
        await ImagePicker().pickMultiImage(imageQuality: 100);
    if (imageFile.isEmpty) {
      Toasts.showToast('未选择图片');
      return;
    } else {
      for (final img in imageFile) {
        state.images.add(File(img.path));
      }
    }
  }

  void onPhoto(int index) {
    Get.to(ShowPhotoGallery(images: state.images, index: index));
  }

  void onDeletePhoto(int index) {
    Get.dialog(defaultDialog(
        content: '确定要删除图片吗？',
        sureFunction: () {
          state.images.removeAt(index);
        }));
  }

  void onToBottom() {
    state.scrollController.animateTo(
        state.scrollController.position.maxScrollExtent,
        duration: const Duration(milliseconds: 300),
        curve: Curves.easeOut);
  }

  void onChangeTitle(String val) {
    state.showTitle.value = val;
  }

  void onChangeData(String val) {
    state.showData.value = val;
    state.contentLength.value = val.length;
  }

// void onToTop() {
//   state.scrollController.animateTo(0,
//       duration: const Duration(milliseconds: 300), curve: Curves.easeOut);
// }

// bool isScrolledHalfway() {
//   double scrollOffset = state.scrollController.offset;
//   double maxScrollExtent = state.scrollController.position.maxScrollExtent;
//   return scrollOffset >= maxScrollExtent / 2;
// }

// bool isOverSize() {
//   if (state.scrollController.position.maxScrollExtent > 1000) {
//     state.isOverSize.value = true;
//     return true;
//   }
//   state.isOverSize.value = false;
//   return false;
// }
}
